#!/usr/bin/python
# -*- coding: utf-8 -*-

"""Project Euler Solution 102

Copyright (c) 2011 by Robert Vella - robert.r.h.vella@gmail.com

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and / or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
"""

import cProfile
from euler.numbers.geometry import vector, point_in_triangle
from euler.file_functions import get_lines

def get_answer():    
    """Question:
    
    Three distinct points are plotted at random on a Cartesian plane, for 
    which -1000 ≤ x, y ≤ 1000, such that a triangle is formed.

    Consider the following two triangles:
    
    A(-340,495), B(-153,-910), C(835,-947)
    
    X(-175,41), Y(-421,-714), Z(574,-645)
    
    It can be verified that triangle ABC contains the origin, whereas triangle
    XYZ does not.
    
    Using triangles.txt, a 27K text file containing the co-ordinates of one 
    thousand "random" triangles, find the number of triangles for which the 
    interior contains the origin.
    
    NOTE: The first two examples in the file represent the triangles in the 
    example given above
    """
    
    origin = vector(0, 0)
    
    def origin_in_triangle(line):
        """Returns true if the triangle expressed in [line] contains the 
        origin.
        """ 
        
        #Parse [line].
        elements = [float(i) for i in line.split(",")]
       
        a = vector(elements[0], elements[1])
        b = vector(elements[2], elements[3])
        c = vector(elements[4], elements[5])
        
        #Return the value.
        return point_in_triangle(origin, a, b, c)
    
    #Return the result.
    return sum(
              1 for line in get_lines("../data/102.txt") 
                if origin_in_triangle(line)
            )
    
if __name__ == "__main__":
    cProfile.run("print(get_answer())")
